/*
 * @Author: xiaosihan
 * @Date: 2022-02-16 23:13:14
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-11-23 13:06:54
 */

import {
  DoubleSide,
  DynamicDrawUsage,
  Material,
  Mesh,
  MeshBasicMaterial,
  MeshLambertMaterial,
  Vector3,
} from "three";
import { PathPointList } from "./PathPointList";
import { PathTubeGeometry } from "./PathTubeGeometry";

export type PipeMeshProps = {
  vector3s: Array<Vector3>;
  radius?: number;
  segments?: number;
};

/**
 * 创建基础的管道模型
 */
export default class PipeMesh extends Mesh<PathTubeGeometry, Material> {
  constructor(props: PipeMeshProps) {
    super();
    this.set(props);
  }

  type = "pipemesh";

  vector3s: Array<Vector3> = []; // 管道上的点

  radius = 1; //管道的半径

  segments = 10; //管道的段数

  pathPointList = new PathPointList();

  material: Material = new MeshLambertMaterial({
    side: DoubleSide,
    color: "#fff",
  });

  // 设置数据
  set(props: PipeMeshProps) {
    this.vector3s = props.vector3s;
    this.radius = props.radius || 1;
    this.segments = props.segments || 10;
    this.pathPointList.set(this.vector3s, props.radius * 2, 10);
    this.geometry = new PathTubeGeometry({
      pathPointList: this.pathPointList,
      options: {
        arrow: true,
        progress: 1,
        radius: props.radius,
        radialSegments: this.segments,
      },
      usage: DynamicDrawUsage,
      transparent: true,
    });
  }

  // 设置指定点的坐标
  setVector(i: number, vector: Vector3) {
    this.vector3s[i].copy(vector);
    this.pathPointList.set(this.vector3s, this.radius * 2, this.segments);
    this.geometry.update(this.pathPointList, { radius: this.radius });
  }

  // 获取指定点的坐标
  getVector(i: number) {
    return this.vector3s[i];
  }

  // 设置最后一个点的坐标
  setLatestVector(vector: Vector3) {
    this.setVector(this.vector3s.length - 1, vector);
  }

  // 回去最后一个点的坐标
  getLatestVector() {
    return this.getVector(this.vector3s.length - 1);
  }
}
